package com.googlecode.afdbaccess.password;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class PasswordHasherTest {
    public static class PasswordPair {
        public final String cleartextPassword;
        public final String hashedPassword;

        public PasswordPair(String cleartextPassword) {
            this.cleartextPassword = cleartextPassword;
            System.out.print("Hashing: \"" + cleartextPassword + "\" ... ");
            this.hashedPassword = PasswordHasher.hashPasswordForStorage(cleartextPassword);
            System.out.println("Result: \"" + hashedPassword + "\"");
        }
    }

    final private static PasswordPair[] passwords = {
            new PasswordPair("testpw"),
            new PasswordPair(null),
            new PasswordPair(""),
            new PasswordPair(" ")
    };
    
    @BeforeClass
    public static void setupClass() {
        // This is just here to get the class load time and static initializing time out of the time for the first test
    }

    @Test
    public void testHashPasswordForStorage() {
        for (PasswordPair password : passwords) {
            assertHashPasswordForStorage(password);
        }
    }

    private void assertHashPasswordForStorage(PasswordPair password) {
        Assert.assertNotNull(password.hashedPassword);
        Assert.assertTrue(password.hashedPassword.length() == 64);
        Assert.assertNotSame("", password.hashedPassword.trim());
        Assert.assertNotSame(password.cleartextPassword, password.hashedPassword);
    }

    @Test
    public void testCheckPassword() {
        for (PasswordPair password : passwords) {
            assertHashAndVerify(password);
        }
    }

    private void assertHashAndVerify(PasswordPair password) {
        Assert.assertTrue(PasswordHasher.checkPassword(password.cleartextPassword, password.hashedPassword));
        Assert.assertFalse(PasswordHasher.checkPassword(password.cleartextPassword, null));
        Assert.assertFalse(password.cleartextPassword != null && PasswordHasher.checkPassword(null, password.hashedPassword));
        Assert.assertFalse("".equals(password.cleartextPassword) == false && PasswordHasher.checkPassword("", password.hashedPassword));
    }
}
